package com.keio.helper;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * @author KEIO  on 2022/1/14.
 * @version 1.0
 */
@Slf4j
public class ClientBootstrapHelper {

    Channel channel = null;

    /**
     * @Description  将工作线程组 与对应的  端口进行绑定  既要监听来自服务器的数据  也有 本地端口的监听
     * @param workerGroup
     * @param channelInitializer
     * @param host
     * @param port
     */
    public synchronized void start(EventLoopGroup workerGroup, ChannelInitializer channelInitializer
                                         ,String host, int port) {
        if(port == 0 || ObjectUtils.isEmpty(host)) {
            log.info("配置文件出错");
            return;
        }
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(channelInitializer);

            /*
            绑定端口
             */
            channel = bootstrap.connect(host, port).sync().channel();
            channel.closeFuture().addListener( (ChannelFutureListener) future -> {
                channel.deregister();
                channel.close();
            });
        } catch (InterruptedException e) {
            channel.close();
            workerGroup.shutdownGracefully();
            log.info("客户端启动器连接异常");
            e.printStackTrace();
        }


    }



}
